package ketnoi;

import java.sql.*;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;


public class KetNoi extends AbstractTableModel{
	/**
	 * 
	 */
	Connection conn;
	Statement stm;
	String current="";
	String[] header;
	Vector<String[]> cache;
	int colNumber;
	private static final long serialVersionUID = 1L;
	public KetNoi(){
		cache=new Vector<String[]>();
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
 public String getColumnName(int i) {
		    return header[i];
	  }
	public int getColumnCount() {
		return colNumber;
	}

	public int getRowCount() {
		return cache.size();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		return ((String[]) cache.elementAt(rowIndex))[columnIndex];
	}
	public void ktrahost(String url,String user,String pass){
		if(url.equals(current)){
			return;
		}
		close();
		current=url;
		try{
			conn=DriverManager.getConnection(url,user,pass);
			stm=conn.createStatement();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void excuteQuery(String q,boolean mok){
		cache=new Vector<String[]>();
		try{
			if(mok){
				ResultSet rs=stm.executeQuery(q);
				ResultSetMetaData meta=rs.getMetaData();
				colNumber=meta.getColumnCount();
				header=new String[colNumber];
				for(int i=1;i<=colNumber;i++){
					header[i-1]=meta.getColumnName(i);
				}
				while(rs.next()){
					String[] record = new String[colNumber];
					for(int i=0;i<colNumber;i++){
						record[i]=rs.getString(i+1);
					}
					cache.addElement(record);
				}
			}else{
				stm.executeUpdate(q);
				
			}
			fireTableChanged(null);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	void close(){
		try{
			if(stm!=null){
				stm.close();
			}
			if(conn!=null){
				conn.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}
